﻿using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WPFLoaders
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            CommandManager.InvalidateRequerySuggested();
        }

        private void OnSave(object sender, RoutedEventArgs routedEventArgs)
        {
            var menuItem = ((MenuItem) sender);
            var contextMenu = (ContextMenu) menuItem.Parent;
            var contentControl = (HeaderedContentControl) contextMenu.PlacementTarget;
            var uiElement = (FrameworkElement)contentControl.Content;

            // http://blogs.msdn.com/b/saveenr/archive/2008/09/22/wpf-xaml-saving-an-animation-as-an-avi-video-file.aspx

            var encoder = new PngBitmapEncoder();
            var target = new RenderTargetBitmap((int)uiElement.ActualWidth, (int)uiElement.ActualHeight, 96, 96, PixelFormats.Pbgra32);

            target.Render(uiElement);
            encoder.Frames.Add(BitmapFrame.Create(target));

            var filename = Path.GetTempFileName() + ".png";
            using (var stream = new FileStream(filename, FileMode.CreateNew, FileAccess.Write))
                encoder.Save(stream);

            Process.Start(filename);   
        }
    }
}
